﻿(function () {
    var app = angular.module('indexApp', ["ui.bootstrap", "ngAnimate", "ngResource", "ngSanitize"]);

    var $my_lang = $my_data;

    var $isSafe = true;
    var $popupModalId = 'PopupLogin';

    app.controller('BodyController', function ($scope, $window, $timeout, $compile, myFactory) {

        $scope.$on('onBeforeUnload', function (e, options) {
            options.message = "All data willl be lost.";
            options.isSafe = $isSafe;
            e.preventDefault();
        });

        $scope.main_init = function () {
            var token = myFactory.getToken();
            var tokenTab = myFactory.getTokenTab();
            if (token) {
                var current = myFactory.getItemById(token);
                var currentTab = current.tabs;
                var tabItem = '';
                if (tokenTab && currentTab) {
                    tabItem = myFactory.getItemById(tokenTab, currentTab);
                }
                $timeout(function () {
                    myFactory.loadContent(current, tabItem);
                }, 100);
            }
            else {
                $scope.mainTemplate = $my_data.sideBarMenu[0];
            }
            // load css for IE or else
            var browser = myFactory.getBrowser();
            var appendFont = function (href) {
                var style_font = document.createElement('link');
                style_font.rel = 'stylesheet';
                style_font.href = href;
                document.head.appendChild(style_font);

            };
            if (myFactory.getBrowser().msie) {
                appendFont('Style/fonts-IE.css')
            }
            else {
                appendFont('Style/fonts.css')
            }

        };

        $scope.$on('broadcastChangeMenu', function () {
            if (myFactory.menuActived && myFactory.menuActived.tabs) {
                var tabActive = myFactory.getItemTabByActive(myFactory.menuActived.tabs);

                var tokenTab = myFactory.getTokenTab();
                if (tokenTab) {
                    tabActive = myFactory.getItemById(tokenTab, myFactory.menuActived.tabs);
                }
                $scope.mainTemplate = tabActive;
            }
            else {
                $scope.mainTemplate = myFactory.menuActived;
            }
        });

        $scope.view_login = function () {
         
            var $PopupLogin = angular.element(document.querySelector('#PopupLogin'));
            if ($PopupLogin.length == 0) {
                myFactory.getContent({
                    method: 'Get',
                    url: 'page/login.html'
                }, function (content, status, headers, config) {
                    var eventClose = "onclick = \"$('#menu-content a[item-id]:eq(0)').trigger('click');\" ";
                    var html = content.replace(/\[Id\]/gi, $popupModalId).replace(/\[Title\]/gi, 'aa').replace(/\[Messages\]/gi, '22').replace(/\[OnClick\]/gi, eventClose);
                    //create DOM elements
                    domElement = angular.element(html);
                    $compile(domElement)($scope);
                    $('body').find('#' + $popupModalId).remove();
                    $('body').append(domElement);
                    $('#' + $popupModalId).modal('show');
                    // console.log('  myFactory.modal', myFactory.modal);
                  
                });
            }
            else {
                $('#' + $popupModalId).modal('show');
            }
           // myFactory.modal.show();
        };


        // window.st
    });
    app.controller('LoginFormController', function ($scope, $window, $timeout, myFactory) {
        $scope.showVerticalText = false;
        $scope.verticalText = '';
        $scope.checkLogin = function () {
            var userName = $scope.username;
            var password = $scope.password;
            $scope.password = '';
            $('#' + $popupModalId).modal('hide');
        };
       
    });

    app.controller('MainContentController', function ($scope, $window, $timeout, myFactory) {
        $scope.showVerticalText = false;
        $scope.verticalText = '';
        $scope.resize = function () {
            var w = angular.element($window);
            var windowHeight = w.height();
            var breadcrumb = $('#main-breadcrumb').outerHeight();
            var token = myFactory.getToken();
            if (token == 1) {
                breadcrumb = 0;
            }
            $scope.height = 'height:' + (windowHeight - 76 - breadcrumb) + 'px';
        };
        angular.element($window).bind('resize', function () {
            $scope.resize();
        });
        $scope.$on('broadcastChangeMenu', function () {
            var token = myFactory.getToken();
            var item = myFactory.getItemById(token);
            $scope.showVerticalText = item.showVerticalText;
            $scope.verticalText = item.title;
            var tabs = myFactory.menuActived.tabs;
            if (tabs) {
                var tokenTab = myFactory.getTokenTab();
                var tabActived = myFactory.getItemTabByActive(tabs);
                if (tokenTab) {
                    tabActived = myFactory.getItemById(tokenTab, tabs);
                }
                $scope.showVerticalText = tabActived.showVerticalText;
            }
            else {
                $scope.showVerticalText = myFactory.menuActived.showVerticalText;
            }
            $timeout($scope.resize, 100);
        });
    });

    app.controller('NavController', function ($scope, $timeout, myFactory) {
        $scope.menu = $my_lang.sideBarMenu;
        $scope.socials = $my_lang.socials;
        $scope.isHover = false;
        $scope.isLoading = false;
        $scope.hoverIn = function () {
            if (!$scope.isLoading)
                $scope.isHover = true;
        };
        $scope.hoverOut = function () {
            $scope.isHover = false;
        };
        $scope.$on('broadcastChangeMenu', function () {
            $scope.isHover = false;
            $scope.isLoading = true;
            $timeout(function () {
                $scope.isLoading = false;
            }, 500);
        });
    });

    app.controller('HomeController', function ($scope, myFactory, appAlert) {
        $scope.item = $my_lang.home;
        $scope.interval = 999995000;
        $scope.action = function (val) {
            var messages = 'Item selected :: ' + (val + 1),
                $carousel = angular.element(document.querySelector('#my-custom-carousel'));
            var option = { type: 10, message: messages };
            var $carouselli = $carousel.find('ol.carousel-indicators li:eq(' + val + ')'),
                css = {},
                offset = $carouselli.offset();
            if (offset) {
                offset.top += 10;
                if (val < 7) {
                    offset.left -= (300 - $carouselli.width()) / 2;
                }
                else {
                    offset.left -= (300 - $carouselli.width());
                }
                angular.extend(css, offset);
            }
            option.css = css;
            var alert = new appAlert(option);
        };
        $scope.slides = $my_lang.home.slides;
        $scope.$on('broadcastChangeMenu', function () {
            if (myFactory.menuActived.id == 1) {
                $scope.interval = 9999 * 1000;
            }
            else {
                $scope.interval = 9999 * 1000;
            }
        });
    });

    app.controller('LanguageController', function ($scope, $location) {
        $scope.items = $my_lang.languages;
        $scope.title_active = $my_lang.languagesActived.title;
        $scope.activedId = $my_lang.languagesActived.countryId;
        $scope.init = function () {

        };
        $scope.change = function (item) {
            var path = $location.path();
            var search = $location.search();
            var param = path + '?' + $.param(search);
            if (param) {
                param = '#' + param;
            }
            $isSafe = false;
            location.href = 'http://' + location.host + item.href + param;
        };
    });

    app.controller('RandomLanguageController', function ($scope, $interval) {
        var count = 0;
        $scope.randomLanguage = "Choose your language";
        $scope.randomCulture = '';
        $scope.arrLanguage = ['Chọn ngôn ngữ của bạn', 'Choose your language'];

        $scope.hoverIn = function () {
            if (angular.isDefined(timer)) {
                $interval.cancel(timer);
                timer = undefined;
            }

        };
        $scope.hoverOut = function () {
            timer = $interval($scope.refresh, 3000);
        };
        $scope.refresh = function () {
            if (count >= $scope.arrLanguage.length)
                count = 0;
            var rand = $scope.arrLanguage[count];
            $scope.randomLanguage = rand;
            count++;
        };
        var timer = $interval($scope.refresh, 3000);
    });

    app.controller('RandomNews', function ($scope, $interval, $element, myFactory) {
        var count = 0;
        $scope.randomText = "";
        $scope.arrNews = [];
        $scope.timeout = 7000;
        var timer = null;
        myFactory.getContent({ url: 'Service/service.asmx/GetNews' }, function (response) {
            $scope.arrNews = response;
            $scope.refresh();
            timer = $interval($scope.refresh, $scope.timeout);
        });
        $scope.hoverIn = function () {
            if (angular.isDefined(timer)) {
                $interval.cancel(timer);
                timer = undefined;
            }
        };
        $scope.hoverOut = function () {
            timer = $interval($scope.refresh, $scope.timeout);
        };
        $scope.refresh = function () {
            $element.hide();
            if (count >= $scope.arrNews.length)
                count = 0;
            var rand = $scope.arrNews[count];
            $scope.randomText = rand.summary;
            $element.fadeIn(1500);
            count++;
        };

    });

    app.controller('FooterMenu', function ($scope, myFactory) {
        $scope.items = $my_lang.footerMenu;
        $scope.actived = '0';
        $scope.loadPage = function (item) {
            myFactory.loadContent(item);
        };
        $scope.$on('broadcastChangeMenu', function () {
            $scope.actived = myFactory.menuActived.id;
        });
    });

    app.controller('HeaderRight', function ($scope, $timeout, myFactory) {
        $scope.items = $my_lang.headerRightMenu;
        $scope.actived = '0';
        $scope.loadPage = function (item) {
            var tabs = item.tabs;
            var targetTab = item.targetTab;
            if (tabs) {
                var tabItem = myFactory.getItemTabByActive(tabs);
                if (targetTab) {
                    tabItem = myFactory.getItemById(targetTab, tabs);
                }
            }
            myFactory.loadContent(item, tabItem);
        };
        $scope.$on('broadcastChangeMenu', function () {
            $scope.actived = myFactory.menuActived.id;
        });
    });

    app.controller('FloatButtonsController', function ($scope, myFactory) {
        $scope.items = $my_lang.floatButtons;
        $scope.load = function (item) {
            var targetId = item.targetId;
            var current = myFactory.getItemById(targetId);
            myFactory.loadContent(current);
        };
        $scope.$on('broadcastChangeMenu', function () {
            var activeId = myFactory.menuActived.id;
            // button Solutions
            if (activeId == 1) {
                $scope.items[0].show = true;
            }
            else {
                $scope.items[0].show = false;
            }
            // button TryoutSignup
            if (activeId == $scope.items[1].targetId) {
                $scope.items[1].show = false;
            }
            else {
                $scope.items[1].show = true;
            }
        });
    });

    app.controller('TryoutSignupController', function ($scope, $compile, myFactory) {
        $scope.thisForm = '';
        $scope.item = $my_lang.tryoutSignup;
        $scope.setForm = function (formName) {
            $scope.thisForm = formName;
        };
        $scope.data = {};
        $scope.data.action = $scope.item.action.list[0];
        $scope.keydown = function (event) {
            var formValid = $scope[$scope.thisForm].$valid;
            var key = event.which || event.keyCode;
            if (key == 9) {
                if (typeof formValid != 'undefined') {
                    if (!formValid) {
                        var $ctrl = $element.find('[tabindex=1]');
                        $ctrl.focus().select();
                        event.preventDefault();
                    }
                }
            }
        };

        $scope.submitForm = function (isValid) {
            var emailTo = 'sales@pmsa.com.vn';
            //emailTo = 'vinh.t.trieu@pmsa.com.vn';
            var name = $scope.data.name || '';
            var note = $scope.data.note || '';
            var email = $scope.data.email;
            var phone = $scope.data.phone || '';
            var action = $scope.data.action || '';

            var inputValue = '<InputValue Function="SaveSignupInfo"/><RequestParams Action="' + action.value + '" Email="' + email + '" Name="' + name + '" Phone="' + phone + '" Note="' + note + '" />';
            var content = '[HTML]';
            content += 'Action: ' + action.text;

            if (name)
                content += '<br/>Name: ' + name;
            if (email)
                content += '<br/>Email: ' + email;
            if (phone)
                content += '<br/>Phone: ' + phone;
            if (note)
                content += '<br/>Note: ' + note;

            $scope.data.locked = true;
            myFactory.modal.show();
            myFactory.getContent({
                url: 'Service/service.asmx/CallCenterProcess',
                params: {
                    strAddrTo: emailTo,
                    strSubject: 'Tryout Signup',
                    strInputValue: encodeURIComponent(inputValue),
                    strBody: encodeURIComponent(content)
                }
            }, function (result) {
                var title = $scope.item.submit.title;
                var messages = '';
                if (result == '1') {
                    messages = $scope.item.submit.success;
                    $scope.data = {};
                    $scope[$scope.thisForm].$setPristine();
                    $scope.data.action = $scope.item.action.list[0];
                }
                else {
                    messages = $scope.item.submit.error;
                }
                myFactory.getContent({
                    method: 'Get',
                    url: 'Popup/Alert.html'
                }, function (content, status, headers, config) {
                    var popupModalId = 'PopupAlert';
                    var eventClose = "onclick = \"$('#menu-content a[item-id]:eq(0)').trigger('click');\" ";
                    var html = content.replace(/\[Id\]/gi, popupModalId).replace(/\[Title\]/gi, title).replace(/\[Messages\]/gi, messages).replace(/\[OnClick\]/gi, eventClose);
                    //create DOM elements
                    domElement = angular.element(html);
                    $compile(domElement)($scope);
                    $('body').find('#' + popupModalId).remove();
                    $('body').append(domElement);
                    $('#' + popupModalId).modal('show');
                    myFactory.modal.hide();
                });
            }, function () {
                myFactory.modal.hide();
                $scope.data.locked = false;
            });
        };
    });

    app.controller('TradeMarksController', function ($scope, myFactory) {
        $scope.items = $my_lang.floatButtons;
        $scope.load = function (item) {
            var targetId = item.targetId;
            var current = myFactory.getItemById(targetId);
            myFactory.loadContent(current);
        };
    });


    app.controller('ShopSignController', function ($scope, $timeout, $element, $compile, myFactory, gMapsInitializer) {
        $scope.isShowMap = false;
        $scope.thisForm = '';
        $scope.item = $my_lang.contactUs;
        $scope.map = null;
        $scope.marker = null;
        $scope.positionCurrent = null;
        $scope.setForm = function (formname) {
            $scope.thisForm = formname;
        };
        $scope.init = function () {

        };


        $scope.submitForm = function () {
            var emailTo = 'sales@pmsa.com.vn';
            var name = $scope.data.name || '';
            var email = $scope.data.email;
            var phone = $scope.data.phone || '';
            var messages = $scope.data.messages || '';

            var inputValue = '<InputValue Function="ContactUs"/><RequestParams Email="' + email + '" Name="' + name + '" Phone="' + phone + '" Messages="' + messages + '" />';
            var content = '[HTML]';
            if (name)
                content += '<br/>Name: ' + name;
            if (email)
                content += '<br/>Email: ' + email;
            if (phone)
                content += '<br/>Phone: ' + phone;
            if (messages)
                content += '<br/>Messages: ' + messages;

            $scope.data.locked = true;
            myFactory.modal.show();
            myFactory.getContent({
                url: 'Service/service.asmx/CallCenterProcess',
                params: {
                    strAddrTo: emailTo,
                    strSubject: 'Tryout Signup',
                    strInputValue: encodeURIComponent(inputValue),
                    strBody: encodeURIComponent(content)
                }
            }, function (result) {
                var title = $scope.item.submit.title;
                var messages = '';
                if (result == '1') {
                    messages = $scope.item.submit.success;
                    $scope.data = {};
                    $scope[$scope.thisForm].$setPristine();
                }
                else {
                    messages = $scope.item.submit.error;
                }
                myFactory.getContent({
                    method: 'Get',
                    url: 'Popup/Alert.html'
                }, function (content, status, headers, config) {
                    var popupModalId = 'PopupAlert';
                    var eventClose = "onclick = \"$('#menu-content a[item-id]:eq(0)').trigger('click');\" ";
                    var html = content.replace(/\[Id\]/gi, popupModalId).replace(/\[Title\]/gi, title).replace(/\[Messages\]/gi, messages).replace(/\[OnClick\]/gi, eventClose);
                    //create DOM elements
                    domElement = angular.element(html);
                    $compile(domElement)($scope);
                    $('body').find('#' + popupModalId).remove();
                    $('body').append(domElement);
                    $('#' + popupModalId).modal('show');
                    myFactory.modal.hide();
                });
            }, function () {
                myFactory.modal.hide();
            });
        };
    });


    app.controller('ContactUsController', function ($scope, $timeout, $element, $compile, myFactory, gMapsInitializer) {
        $scope.isShowMap = false;
        $scope.thisForm = '';
        $scope.item = $my_lang.contactUs;
        $scope.map = null;
        $scope.marker = null;
        $scope.positionCurrent = null;
        $scope.setForm = function (formname) {
            $scope.thisForm = formname;
        };
        $scope.init = function () {
            gMapsInitializer.mapsInitialized.then(function () {
                var lat = 51.508742;
                var lng = -0.120850;
                if ($scope.positionCurrent) {
                    lat = $scope.positionCurrent.lat;
                    lng = $scope.positionCurrent.lng;
                }
                var latlng = new google.maps.LatLng(lat, lng)
                var mapOption = {
                    center: latlng,
                    zoom: 17,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var $elm = angular.element($element).find('#googleMaps');
                $scope.map = new google.maps.Map($elm[0], mapOption);
                $scope.marker = new google.maps.Marker({
                    position: latlng
                });
                $scope.marker.setMap($scope.map);
            });
        };
        $scope.loadMap = function (item) {
            var showMap = item.showMap;
            if (showMap) {
                item.showMap = false;
                $scope.isShowMap = false;
            }
            else {
                item.showMap = true;
                $scope.isShowMap = true;
            }
            angular.forEach($scope.item.address.region, function (value, key) {
                if (value.showMap && value != item) {
                    value.showMap = false;
                }
            });
            //maps
            var position = item.position;
            $scope.positionCurrent = position;
            if (typeof google != 'undefined' && $scope.map) {
                $timeout(function () {
                    google.maps.event.trigger($scope.map, "resize");
                    var latLng = new google.maps.LatLng(position.lat, position.lng);
                    $scope.map.setCenter(latLng);
                    $scope.marker.setPosition(latLng);
                }, 100);
            }
        };

        $scope.submitForm = function () {
            var emailTo = 'sales@pmsa.com.vn';
            var name = $scope.data.name || '';
            var email = $scope.data.email;
            var phone = $scope.data.phone || '';
            var messages = $scope.data.messages || '';

            var inputValue = '<InputValue Function="ContactUs"/><RequestParams Email="' + email + '" Name="' + name + '" Phone="' + phone + '" Messages="' + messages + '" />';
            var content = '[HTML]';
            if (name)
                content += '<br/>Name: ' + name;
            if (email)
                content += '<br/>Email: ' + email;
            if (phone)
                content += '<br/>Phone: ' + phone;
            if (messages)
                content += '<br/>Messages: ' + messages;

            $scope.data.locked = true;
            myFactory.modal.show();
            myFactory.getContent({
                url: 'Service/service.asmx/CallCenterProcess',
                params: {
                    strAddrTo: emailTo,
                    strSubject: 'Tryout Signup',
                    strInputValue: encodeURIComponent(inputValue),
                    strBody: encodeURIComponent(content)
                }
            }, function (result) {
                var title = $scope.item.submit.title;
                var messages = '';
                if (result == '1') {
                    messages = $scope.item.submit.success;
                    $scope.data = {};
                    $scope[$scope.thisForm].$setPristine();
                }
                else {
                    messages = $scope.item.submit.error;
                }
                myFactory.getContent({
                    method: 'Get',
                    url: 'Popup/Alert.html'
                }, function (content, status, headers, config) {
                    var popupModalId = 'PopupAlert';
                    var eventClose = "onclick = \"$('#menu-content a[item-id]:eq(0)').trigger('click');\" ";
                    var html = content.replace(/\[Id\]/gi, popupModalId).replace(/\[Title\]/gi, title).replace(/\[Messages\]/gi, messages).replace(/\[OnClick\]/gi, eventClose);
                    //create DOM elements
                    domElement = angular.element(html);
                    $compile(domElement)($scope);
                    $('body').find('#' + popupModalId).remove();
                    $('body').append(domElement);
                    $('#' + popupModalId).modal('show');
                    myFactory.modal.hide();
                });
            }, function () {
                myFactory.modal.hide();
            });
        };
    });

    app.controller('ClientAccessController', function ($scope, $element, $compile, $timeout, myFactory) {
        $scope.thisForm = '';
        $scope.data = {};
        $scope.item = $my_lang.clientAccess;
        $scope.setForm = function (formName) {
            $scope.thisForm = formName;
        };

        $scope.keydown = function (event) {
            var formValid = $scope[$scope.thisForm].$valid;
            var key = event.which || event.keyCode;
            if (key == 9) {
                if (typeof formValid != 'undefined') {
                    if (!formValid) {
                        var $ctrl = $element.find('[tabindex=1]');
                        $ctrl.focus().select();
                        event.preventDefault();
                    }
                }
            }
        };

        $scope.submitForm = function () {
            var formValid = $scope[$scope.thisForm].$valid;
            if (!formValid) {
                return false;
            }
            var clientGroup = angular.uppercase($scope.data.clientGroup);
            var username = $scope.data.username;
            var password = $scope.data.password || '';
            var remember = $scope.data.remember ? '1' : '0';

            $scope.submiting = true;
            myFactory.modal.show();
            var service_url = 'http://' + clientGroup + '.pmsa.com.vn/Beta/mods/account/autologin.aspx';
            //var service_url = 'http://localhost/iMarkets/Mods/account/autologin.aspx?cg=djd';
            $.post(service_url, {
                iuser: username,
                ipass: password
            }).done(function (data) {
                if (data) {
                    data = $.parseJSON(data);
                    if (data.status == 1) {
                        $isSafe = false;
                        location.href = data.url + '?itoken=' + data.token;
                    }
                    else {
                        myFactory.showAlert({
                            id: 'ClientAccess',
                            type: 'danger',
                            message: data.message
                        });
                    }
                }
                else {

                }
                $timeout(function () {
                    myFactory.modal.hide();
                    $scope.submiting = false;
                }, 500);
            }).fail(function () {
                myFactory.showAlert({
                    id: 'ClientAccess',
                    type: 'danger',
                    message: 'Company Code not found!'
                });
                myFactory.modal.hide();
                $scope.submiting = false;
            });
            /////////////////////////////////////////////////////
            return;
            myFactory.getContent({
                url: service_url,
                method: 'POST',
                data: {
                    iuser: username,
                    ipass: password
                }
            }, function (data) {
                if (data) {
                    if (data.status == 1) {
                        $isSafe = false;
                        location.href = data.url;
                    }
                    else {
                        myFactory.showAlert({
                            id: 'ClientAccess',
                            message: data.message
                        });
                    }
                }
                else {
                    console.log('Page not found');
                }
                myFactory.modal.hide();
                $scope.submiting = false;
            }, function (result) {
                myFactory.modal.hide();
                $scope.submiting = false;
            });
        };
    });

    app.controller('BreadcrumbController', function ($scope, $timeout, $window, myFactory) {
        $scope.show = false;
        $scope.title_active = '&nbsp;';
        $scope.items = [];
        $scope.tabs = [];
        $scope.tabActived = '';
        $scope.init = function () {
            for (var i = 0; i <= 7; i++) {
                $scope.items.push({
                    index: i,
                    title: '',
                    href: ''
                });
            }
        };

        $scope.load = function (item) {
            if (item) {
                myFactory.loadContent(item);
            }
            else {
                var item_def = myFactory.getItemTabByActive($scope.tabs);
                if (item_def) {
                    $timeout(function () {
                        myFactory.loadContent(item_def);
                    }, 100);
                }
            }
        };
        $scope.resize = function (options) {
            $('.main-breadcrumb-header .main-breadcrumb-bar0').css('width', 'auto');
            if (options && options.title) {
                $('.main-breadcrumb-header .main-breadcrumb-bar0').text(options.title);
            }
            var width_breadcrumb = $('.main-breadcrumb-header').width();
            var width_breadcrumb_title = $('.main-breadcrumb-header .main-breadcrumb-bar0').width() + 20;
            var width_breadcrumb_bars = width_breadcrumb - width_breadcrumb_title;
            var width_breadcrumb_bar = Math.floor(width_breadcrumb_bars / 7);
            width_breadcrumb_title = width_breadcrumb_title + (width_breadcrumb_bars % 7);
            $('.main-breadcrumb-header .main-breadcrumb-bar0').width(width_breadcrumb_title);
            $('.main-breadcrumb-header .main-breadcrumb-bar').not('.main-breadcrumb-bar0').width(width_breadcrumb_bar);
        };
        angular.element($window).on('resize', function () {
            $timeout($scope.resize, 100);
        });
        $scope.$on('broadcastChangeMenu', function () {
            var tabs = myFactory.menuActived.tabs;
            var context = myFactory.menuActived.context;
            $scope.tabActived = { id: 0 };
            if (context == 'tab') {
                $scope.tabActived = myFactory.menuActived;
            }
            else {
                $scope.title_active = myFactory.menuActived.title;
                $scope.tabs = [];
                if (tabs && tabs.length) {
                    angular.forEach(tabs, function (value, key) {
                        $scope.tabs.push(value);
                    });
                    var tabToken = myFactory.getTokenTab();
                    if (tabToken) {
                        $scope.tabActived = myFactory.getItemById(tabToken, tabs);
                    }
                    else {
                        $scope.tabActived = myFactory.getItemTabByActive(tabs);
                    }
                }
                else {
                    $scope.tabs[0] = myFactory.menuActived;
                }

            }
            if (myFactory.menuActived.id == 1) {
                $scope.show = false;
            }
            else {
                $scope.show = true;
            }

            $timeout($scope.resize);
        });

    });

    app.controller('HeadTextActivedController', function ($scope, $timeout, myFactory) {
        $scope.textActived = '';
        $scope.subTextActived = '';
        $scope.itemActived = {};
        $scope.itemParent = {};
        $scope.hasSub = false;

        $scope.load = function () {
            myFactory.setTokenTab(null);
            myFactory.loadContent($scope.itemParent);
        };
        $scope.$on('broadcastChangeMenu', function () {
            $scope.itemActived = myFactory.menuActived;

            var tabs = myFactory.menuActived.tabs;

            if (tabs) {
                var tabActived = {};
                var tabToken = myFactory.getTokenTab();
                if (tabToken) {
                    tabActived = myFactory.getItemById(tabToken, tabs);
                }
                else {
                    tabActived = myFactory.getItemTabByActive(tabs);
                }

                $scope.textActived = myFactory.menuActived.title;
                $scope.subTextActived = tabActived.title;
                $scope.itemParent = myFactory.menuActived;
                $scope.hasSub = true;
            }
            else {
                $scope.subTextActived = '';
                $scope.hasSub = false;
                var context = $scope.itemActived.context;
                //console.log('myFactory.menuActived', myFactory.menuActived);
                switch (context) {
                    case 'tab':
                        $scope.subTextActived = $scope.itemActived.title;
                        $scope.hasSub = true;
                        break;
                    case 'header':
                    case 'footer':
                        var homeItem = $my_lang.sideBarMenu[0];
                        $scope.subTextActived = $scope.itemActived.title;
                        $scope.textActived = homeItem.title;
                        $scope.hasSub = true;
                        $scope.itemParent = homeItem;
                        break;
                    default:
                        $scope.textActived = $scope.itemActived.title;
                        break;
                }
            }
        });
    });
    //directive
    app.directive('menu', function () {
        return {
            restrict: 'A',
            scope: {
                menu: '=menu',
                cls: '=ngClass'
            },
            replace: true,
            template: '<ul><li ng-repeat="item in menu" menu-item="item"></li></ul>',
            link: function (scope, element, attrs) {
                element.addClass(attrs.class);
                element.addClass(scope.cls);
            }
        };
    });

    app.directive('menuItem', function ($compile, $timeout, myFactory) {
        return {
            restrict: 'A',
            replace: true,
            scope: {
                item: '=menuItem'
            },
            template: '<li ng-class="{active:item.id==actived}"><a href="javascript:void(0)" item-href="javascript:void(0)" item-id="{{item.id}}"><i class="fa fa-{{item.icon}} fa-lg" ng-show="item.icon"></i> {{item.title}}</a></li>',
            link: function (scope, element, attrs) {
                if (scope.item) {
                    if (scope.item.submenu) {
                        element.addClass('collapsed');
                        element.find('a:eq(0)').append('<span class="arrow"></span>');
                        element.find('a:eq(0)').attr('data-toggle', 'collapse');
                        element.find('a:eq(0)').attr('data-target', '#sub-' + scope.item.id);
                        var $submenu = $('<div menu="item.submenu" id="sub-{{item.id}}" class="sub-menu collapse"></div>');
                        element.append($submenu);
                    }
                    element.find('a').attr('ng-click', 'load()');
                    if (scope.item.actived) {
                        $('.box-pageActived-text').text(scope.item.title);
                    }
                }
                $compile(element.contents())(scope);
            },
            controller: function ($scope, $element) {
                $scope.actived = '1';
                $scope.load = function () {
                    var callback = null;
                    var tabs = $scope.item.tabs;
                    if (tabs) {
                        var tabItem = myFactory.getItemTabByActive(tabs);
                        if (tabItem) {
                            callback = function () {
                                $timeout(function () { myFactory.loadContent(tabItem); }, 200);
                            };
                        }
                    }
                    myFactory.loadContent($scope.item, callback);
                };
                $scope.$on('broadcastChangeMenu', function () {
                    if (myFactory.menuActived.context == 'tab') {
                    }
                    else {
                        $scope.actived = myFactory.menuActived.id;
                    }
                });
            }
        };
    });

    app.directive('directiveLogo', function ($interval) {
        return {
            restrict: 'A',
            replace: true,
            template: function () {
                var ret = '';
                var isFlashExists = swfobject.hasFlashPlayerVersion('1') ? true : false;
                if (isFlashExists) {
                    ret = ''
                    + '<object type="application/x-shockwave-flash"'
                        + ' data="images/logo.swf"'
                        + ' width="56" height="56">'
                        + ' <param name="movie" value="images/logo.swf" />'
                        + ' <param name="quality" value="high"/>'
                        + ' <param name="wmode" value="transparent">'
                    + ' </object>';
                }
                else {
                    var arr = [{ id: '1', title: 'logo 1', href: 'images/logo/logo1.png' }, { id: '2', title: 'logo 2', href: 'images/logo/logo2.png' }];
                    ret = '<ul directive-logo-images>';
                    $.each(arr, function (index, item) {
                        ret += '<li><img src="' + item.href + '" /></li>';
                    });
                    ret += '</ul>';
                }
                return ret;
            }
        };
    });

    app.directive('directiveLogoImages', function ($interval) {
        return function (scope, element, attrs) {
            var timer; // so that we can cancel the time updates
            var $li = element.find('li');
            var count = 0;
            function updateTime() {
                if (count >= $li.length)
                    count = 0;
                $li.removeClass('show');
                element.find('li').eq(count).addClass('show');
                count++;
            }
            scope.$watch(element, function (value) {
                updateTime();
            });

            timer = $interval(updateTime, 5000);
        }
    });

    app.directive('directiveMaskPhone', function ($timeout) {
        return function (scope, element, attrs) {
            if (typeof element.intlTelInput == 'function') {
                element.intlTelInput({
                    preferredCountries: $my_lang.languagesActived.phone
                });
            }
        }
    });

    app.directive('directiveAutoFocus', function ($timeout) {
        return function (scope, element, attrs) {
            $timeout(function () {
                element.focus();
            }, 100);
        }
    });

    app.directive('directiveEndIndex', function ($timeout) {
        return {
            restrict: 'A',
            scope: {
                form: '=directiveEndIndex'
            },
            link: function ($scope, $element) {
                $scope.$watch('form', function (elm) {
                    $timeout(function () {
                        var formName = $scope.form.$name;
                        $element.unbind('keydown');
                        $element.keydown(function (event) {
                            var key = event.which || event.keyCode;
                            if (key == 9) {
                                event.preventDefault();
                                $('[name=' + formName + ']').find('[tabindex=1]').focus().select();
                                return false;
                            }
                        });
                    }, 100);
                });
            }
        }
    });
    //directive-next-end-index
    app.directive('directiveNextEndIndex', function ($timeout) {
        return {
            restrict: 'A',
            scope: {
                form: '=directiveNextEndIndex'
            },
            link: function ($scope, $element) {
                $scope.$watch('form', function (elm) {
                    $timeout(function () {
                        var formName = $scope.form.$name;

                        $element.unbind('keydown');
                        $element.keydown(function (event) {
                            var formValid = $scope.form.$valid;
                            var key = event.which || event.keyCode;
                            if (key == 9) {
                                if (!formValid) {
                                    var $ctrl = $('[name=' + formName + ']').find('[tabindex=1]');
                                    $ctrl.focus().select();
                                    event.preventDefault();
                                }
                            }
                        });
                    });
                });
            }
        }
    });
    // factory
    app.factory('myFactory', function ($http, $compile, $rootScope, $timeout, $location) {
        var myFactory = {};

        myFactory.getContent = function (config, success, error) {
            $http(config).success(success).error(error);
            //var method = angular.toUpperCase(config.method);
            //switch (method) {
            //    case 'POST':
            //        $http(config).success(success).error(error);
            //        break;
            //    default:
            //        $http(config).success(success).error(error);
            //        break;
            //}


        };
        /* Change Country */
        myFactory.myLang = $my_data;
        myFactory.changeCountry = function (country) {
            $timeout(myFactory.broadcastCountry, 100);
        };
        myFactory.broadcastCountry = function () {
            $rootScope.$broadcast('broadcastChangeCountry');
        };

        myFactory.loadContent = function (options, tabTarget) {

            var scope;
            var type = options.type;
            var id = options.id;
            var tabs = options.tabs;
            var href = options.href;
            var title = options.title;
            var context = options.context;


            myFactory.setTokenTab(null);
            document.title = 'NIPPON: ' + title;
            var itemActived = options;
            if (context == 'tab') {
                myFactory.setTokenTab(id);
            }
            else {
                if (options.tabs && options.tabs.length) {
                    var tabActive = myFactory.getItemTabByActive(options.tabs);
                    if (tabTarget) {
                        tabActive = tabTarget;
                    }
                    myFactory.setTokenTab(tabActive.id);
                    document.title = 'NIPPON: ' + tabActive.title;

                }
                myFactory.setToken(id);
            }
            document.title = 'NIPPON: ' + options.title;

            myFactory.menuActived = itemActived;
            $timeout(myFactory.broadcastMenu, 100);
        };
        myFactory.broadcastMenu = function () {
            $rootScope.$broadcast('broadcastChangeMenu');
        };
        myFactory.compileHtml = function (html) {
            var scope = $rootScope.$new();
            var domElement = angular.element(html);
            $compile(domElement)(scope);
            return domElement;
        };
        myFactory.modal = {
            show: function () {
                $('#modal-loading').show();
            },
            hide: function () {
                $('#modal-loading').hide();
            }
        };

        myFactory.getItemById = function (token, obj) {
            var current = '';
            if (token) {
                if (obj) {
                    $.each(obj, function (index, item) {
                        if (item.id == token) {
                            current = item;
                        }
                    });
                }
                else {
                    $.each($my_lang.sideBarMenu, function (index, item) {
                        if (item.id == token) {
                            current = item;
                        }
                    });

                    if (typeof current.id == 'undefined') {
                        $.each($my_lang.footerMenu, function (index, item) {
                            if (item.id == token) {
                                current = item;
                            }
                        });
                    }
                    if (typeof current.id == 'undefined') {
                        $.each($my_lang.headerRightMenu, function (index, item) {
                            if (item.id == token) {
                                current = item;
                            }
                        });
                    }
                }
            }
            return current;
        };
        myFactory.getItemTabByActive = function (tabs) {
            var result = null;
            $.each(tabs, function (index, item) {
                if (item.active) {
                    result = item;
                }
            });
            return result;
        };
        myFactory.setToken = function (token) {
            $location.path(token);
        };
        myFactory.getToken = function () {
            var path = $location.path() || '1';
            var token = path.replace('/', '');
            return token;
        };
        myFactory.setTokenTab = function (tab) {
            $location.search({ tab: tab });
        };
        myFactory.getTokenTab = function () {
            var search = $location.search();
            var tab = search.tab;
            return tab;
        };
        myFactory.getBrowser = function () {
            var version = 0;
            var fn_getVersion = function () {
                var ua = navigator.userAgent, tem,
                M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
                if (/trident/i.test(M[1])) {
                    tem = /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || [];
                    return 'IE ' + (tem[1] || '');
                }
                M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
                if ((tem = ua.match(/version\/([\.\d]+)/i)) != null)
                    M[2] = tem[1];
                return M.join(' ');
            };
            var arrVersion = fn_getVersion().split(' ');
            if (arrVersion && arrVersion.length) {
                name = arrVersion[0];
                version = arrVersion[1];
            }
            var userAgent = navigator.userAgent.toLowerCase();
            // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
            var isOpera = !!window.opera || userAgent.indexOf(' opr/') >= 0;
            // Firefox 1.0+
            var isFirefox = typeof InstallTrigger !== 'undefined';
            // At least Safari 3+: "[object HTMLElementConstructor]"
            var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
            // Chrome 1+
            var isChrome = !!window.chrome && !isOpera;
            // At least IE6
            var isIE = !!document.documentMode;

            var browser = {
                name: name,
                version: version,
                msie: isIE,
                firefox: isFirefox,
                mozilla: isFirefox,
                chrome: isChrome,
                safari: isSafari,
                opera: isOpera
            };
            return browser;
        };
        myFactory.showAlert = function (opts) {
            var options = {
                id: '',
                type: 'success',
                title: 'RESULT',
                message: ''
            };
            angular.extend(options, opts);
            myFactory.getContent({
                method: 'Get',
                url: 'Popup/Alert.html'
            }, function (content, status, headers, config) {
                var popupModalId = 'PopupAlert-' + options.id;
                var message = options.message;
                var title = 'RESULT';
                var type = options.type;
                var html = content.replace(/\[Id\]/gi, popupModalId).replace(/\[Type\]/gi, type).replace(/\[Title\]/gi, title).replace(/\[Messages\]/gi, message).replace(/\[OnClick\]/gi, '');
                //create DOM elements
                domElement = angular.element(html);
                var scope = $rootScope.$new();
                $compile(domElement)(scope);
                var $body = angular.element('body');
                $body.find('#' + popupModalId).remove();
                $body.append(domElement);
                angular.element('#' + popupModalId).modal('show');
            });
        };
        return myFactory;
    });

    app.factory('beforeUnload', function ($rootScope, $window) {
        //Events are broadcast outside the Scope Lifecycle
        $window.onbeforeunload = function (e) {
            var options = {
                isSafe: true
            };
            var event = $rootScope.$broadcast('onBeforeUnload', options);
            if (options.isSafe) {
                return options.message;
            }
        };

        $window.onunload = function () {
            $rootScope.$broadcast('onUnload');
        };

        return {};
    });

    app.factory('appAlert', ['$http', function ($http) {
        var $body = angular.element(document.querySelector('body')),
            currentId = 'app-alert';

        function getAlert(id) {
            if (id == undefined) id = currentId;
            return $body.find('#' + id);
        };

        var alert = function (option) {
            if (option) {
                var title = option.title || 'Result',
                    template = '',
                    message = option.message || 'Alert message content',
                    id = option.id,
                    css = option.css || undefined,
                    setting = option.setting || undefined;

                var $alert = getAlert(id);
                if ($alert.length) { //update
                    $alert.remove();
                }

                switch (option.type) {
                    case 0: //success
                        break;

                    case 1: //info
                        break;

                    case 2: //confirm
                        break;

                    case 9: //error
                        break;

                    case 10: //info no title
                        setting = { backdrop: 'static', show: true, keyboard: true };
                        template = '<div class="modal fade app-modal pos-absolute" id="' + currentId + '">'
                                        + '<div class="modal-dialog modal-sm">'
                                            + '<div class="modal-content">'
                                                + '<div class="modal-body text-center">'
                                                + message
                                                + '</div>'
                                                + '<div class="modal-footer">'
                                                    + '<button type="button" class="btn btn-success" data-dismiss="modal">OK</button>'
                                                + '</div>'
                                            + '</div>'
                                        + '</div>'
                                    + '</div>';
                        break;
                }

                $body.append(template);

                $alert = getAlert();
                if (css) {
                    $alert.find('.modal-dialog').css(css);
                }
                $alert.modal(setting);
            }
        };

        alert.prototype.show = function (flag) {
            var $alert = getAlert();
            if (flag == undefined || flag) { //show
                $alert.modal('show');
            }
            else {//hide
                $alert.modal('hide');
            }
        };

        return alert;
    }]);

    app.factory('gMapsInitializer', function ($window, $q) {
        var mapsDefer = $q.defer();
        var asyncUrl = 'https://maps.googleapis.com/maps/api/js?v=3.exp&callback=';
        var asyncLoad = function (callbackName) {
            var script = document.createElement('script');
            script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&callback=' + callbackName;
            document.body.appendChild(script);
        };
        $window.googleMapsInitialized = function () {
            mapsDefer.resolve();
        };
        asyncLoad('googleMapsInitialized');
        return {
            mapsInitialized: mapsDefer.promise
        };
    });

    app.run(function (beforeUnload) {
        // Must invoke the service at least once
    });
})();